unit Push.WinService;


interface

{$IFDEF MSWINDOWS}
uses
  Vcl.SvcMgr, Forms, Windows, SysUtils, WinSvc;


Type
  IServiceModule = interface
    function DoStart(IsServ: boolean): boolean;
    function DoStop(IsServ: boolean): boolean;
  end;

function Installing: Boolean;
function StartService(SServiceName: string): Boolean;

{$ENDIF}

implementation


{$IFDEF MSWINDOWS}

function Installing: Boolean;
begin
  Result := FindCmdLineSwitch('INSTALL',['-','\','/'], True) or // Do not localize
            FindCmdLineSwitch('UNINSTALL',['-','\','/'], True); // Do not localize
end;

// Added verbatim from Raid# 255258
function  LocalSystemUserName : string;
const
 SECURITY_LOCAL_SYSTEM_RID: DWORD = $00000012;
 SECURITY_NT_AUTHORITY: SID_IDENTIFIER_AUTHORITY = (Value:(0,0,0,0,0,5));
var
  sia: SID_IDENTIFIER_AUTHORITY;
  NameSize,
  DomainSize: DWORD;
  pInteractiveSid : PSID;
  UsrName,DomainName: string;
  SidNameUse: SID_NAME_USE;
begin
  Result := '';
  sia := SECURITY_NT_AUTHORITY;
  Win32Check(AllocateAndInitializeSid(sia,1,SECURITY_LOCAL_SYSTEM_RID,
        0,0,0, 0, 0, 0, 0, pInteractiveSid ));
  if pInteractiveSid <> nil then
    try
      NameSize := 1024;
      DomainSize := 1024;
      Inc(NameSize);
      Inc(DomainSize);
      SetLength(UsrName,NameSize);
      SetLength(DomainName,DomainSize);
      Win32Check(LookupAccountSID(nil, pInteractiveSid, PChar(UsrName), NameSize,
        PChar(DomainName), DomainSize, SidNameUse));
      SetLength(UsrName,NameSize);
      Result := UsrName;
    finally
      FreeSid(pInteractiveSid);
    end;
end;

function StartService(SServiceName: string): Boolean;
var
  Mgr, Svc: Integer;
  UserName, ServiceStartName: string;
  Config: Pointer;
  Size: DWord;
begin
  Result := False;
  Mgr := OpenSCManager(nil, nil, SC_MANAGER_ALL_ACCESS);
  if Mgr <> 0 then
  begin
    Svc := OpenService(Mgr, PChar(SServiceName), SERVICE_ALL_ACCESS);
    Result := Svc <> 0;
    if Result then
    begin
      QueryServiceConfig(Svc, nil, 0, Size);
      Config := AllocMem(Size);
      try
        QueryServiceConfig(Svc, Config, Size, Size);
        ServiceStartName := PQueryServiceConfig(Config)^.lpServiceStartName;
        if CompareText(ServiceStartName, 'LocalSystem') = 0 then // Do not localize
          ServiceStartName := LocalSystemUserName;
      finally
        Dispose(Config);
      end;
      CloseServiceHandle(Svc);
    end;
    CloseServiceHandle(Mgr);
  end;
  if Result then
  begin
    Size := 256;
    SetLength(UserName, Size);
    GetUserName(PChar(UserName), Size);
    SetLength(UserName, StrLen(PChar(UserName)));
    Result := CompareText(UserName, ServiceStartName) = 0;
  end;
end;

{$ENDIF}
end.


